package com.jeeplus.invoice.api;

import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.invoice.qrcode.service.YxfpQrcodeService;
import com.jeeplus.invoice.qrcode.service.dto.YxfpQrcodeDTO;
import com.jeeplus.invoice.qrcode.service.mapstruct.YxfpQrcodeWrapper;
import com.jeeplus.invoice.utils.JsonUtil;
import com.jeeplus.invoice.utils.MiniProgramTools;
import com.jeeplus.invoice.utils.PropertiesLoader;
import com.jeeplus.sys.utils.FileKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Api(tags = "越香发票-二维码管理API")
@RestController
@RequestMapping(value = "/invoice/api/qrcode")
public class QrcodeAPI {

    @Autowired
    private YxfpQrcodeService yxfpQrcodeService ;

    @Autowired
    private YxfpQrcodeWrapper yxfpQrcodeWrapper;

    /**
     * 根据二维码ID获取二维码信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据二维码ID获取二维码信息")
    @GetMapping("getQrcodeById")
    public ResponseEntity<YxfpQrcodeDTO> getQrcodeById(String id){
        return ResponseEntity.ok(yxfpQrcodeService.findById(id));
    }

    /**
     * 根据商户ID获取二维码信息
     * @param merchantId
     * @return
     */
    @ApiOperation(value = "根据商户ID获取二维码信息")
    @GetMapping("getQrcodeByMerchantId")
    public ResponseEntity<YxfpQrcodeDTO> getQrcodeByMerchantId(String merchantId){
        return ResponseEntity.ok(yxfpQrcodeService.findByMerchantId(merchantId));
    }

    /**
     * 商家绑定二维码
     * @param merchantId
     * @param qrcodeId
     * @return
     */
    @ApiOperation(value = "商家绑定二维码")
    @PostMapping("bindingQrcode")
    public ResponseEntity<String> bindingQrcode(String merchantId,String qrcodeId){
        YxfpQrcodeDTO yxfpQrcodeDTO = yxfpQrcodeService.findByMerchantId(merchantId);
        if(yxfpQrcodeDTO != null){
            return ResponseEntity.ok("该二维码已被绑定，请联系管理员处理。");
        }
        yxfpQrcodeService.bindingQrcode(merchantId,qrcodeId);
        return ResponseEntity.ok("绑定二维码成功");
    }

    /**
     * 商家解除绑定二维码
     * @param qrcodeId
     * @return
     */
    @ApiOperation(value = "商家解除绑定二维码")
    @PostMapping("unBindingQrcode")
    public ResponseEntity<String> unBindingQrcode(String qrcodeId){
        yxfpQrcodeService.unBindingQrcode(qrcodeId);
        return ResponseEntity.ok("绑定二维码成功");
    }

    /**
     * 根据二维码内容查询商户ID
     * @param content
     * @return
     */
    @ApiOperation(value = "根据二维码内容获取二维码信息")
    @GetMapping("getMerchantIdByContent")
    public ResponseEntity<YxfpQrcodeDTO> getMerchantIdByContent(String content){
        return ResponseEntity.ok(yxfpQrcodeService.getMerchantIdByContent(content));
    }

    /**
     * 生成小程序码
     */
    @ApiOperation(value = "生成小程序码")
    @PostMapping(value="createMiniQR")
    public ResponseEntity<String> createMiniQR(){
        String realPath =  FileKit.getAttachmentDir() + "qrcode/";
        FileUtils.createDirectory(realPath);
        String scene = UUID.randomUUID().toString().replace("-", "");
        String fileName=scene+".png"; //encoderImgId此处二维码的图片名
        try {
            PropertiesLoader p = new PropertiesLoader("/appid.properties");
            String appid = p.getProperty("appid");
            String secret = p.getProperty("appsecret");
            YxfpQrcodeDTO yxfpQrcodeDTO = new YxfpQrcodeDTO();
            Map<String, Object> paraMap = new HashMap<String, Object>();
            //二维码携带参数 不超过32位 参数类型必须是字符串
            paraMap.put("scene", scene);  //存入的参数
            paraMap.put("page", "pages/scan");
            paraMap.put("width", 798);
            byte[] result = MiniProgramTools.getMiniQR(appid, secret, paraMap);
            if(new String(result).startsWith("{")) {
                Map<String, Object> model = JsonUtil.jsonToMap(new String(result));
                if (model.get("errcode") != null) {
                    return ResponseEntity.ok("小程序码生成失败！返回信息：" + new String(result));
                }
            }
            String filePath = realPath + fileName;  //存放路径
            OutputStream os = new FileOutputStream(new File(filePath));
            os.write(result, 0, result.length);
            os.flush();
            os.close();
            yxfpQrcodeDTO.setPath(FileKit.getAttachmentUrl() + "qrcode/" + fileName);
            yxfpQrcodeDTO.setContent(scene);
            yxfpQrcodeDTO.setBindState("0");
            yxfpQrcodeDTO.setMemo("新生成小程序码");
            yxfpQrcodeService.saveOrUpdate(yxfpQrcodeWrapper.toEntity(yxfpQrcodeDTO));
            return ResponseEntity.ok("小程序码生成成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null ;
    }

    /**
     * 批量生成小程序码
     */
    @ApiOperation(value = "批量生成小程序码")
    @PostMapping(value="createBatchMiniQR")
    public ResponseEntity<String> createBatchMiniQR(int num){
        String realPath =  FileKit.getAttachmentDir() + "qrcode/";
        FileUtils.createDirectory(realPath);
        PropertiesLoader p = new PropertiesLoader("/appid.properties");
        String appid = p.getProperty("appid");
        String secret = p.getProperty("appsecret");
        String scene = "" ;
        for(int i=0; i<num;i++){
            scene = UUID.randomUUID().toString().replace("-", "");
            String fileName=scene+".png"; //encoderImgId此处二维码的图片名
            Map<String, Object> paraMap = new HashMap<String, Object>();
            //二维码携带参数 不超过32位 参数类型必须是字符串
            paraMap.put("scene", scene);  //存入的参数
            paraMap.put("page", "pages/scan");
            paraMap.put("width", 798);
            byte[] result = MiniProgramTools.getMiniQR(appid, secret, paraMap);
            if(new String(result).startsWith("{")) {
                Map<String, Object> model = JsonUtil.jsonToMap(new String(result));
                if (model.get("errcode") != null) {
                    return ResponseEntity.ok("小程序码生成失败！返回信息：" + new String(result));
                }
            }
            String filePath = realPath + fileName;  //存放路径
            try {
                OutputStream os = new FileOutputStream(new File(filePath));
                os.write(result, 0, result.length);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            YxfpQrcodeDTO yxfpQrcodeDTO = new YxfpQrcodeDTO();
            yxfpQrcodeDTO.setPath(FileKit.getAttachmentUrl() + "qrcode/" + fileName);
            yxfpQrcodeDTO.setContent(scene);
            yxfpQrcodeDTO.setBindState("0");
            yxfpQrcodeDTO.setMemo("新生成小程序码");
            yxfpQrcodeService.saveOrUpdate(yxfpQrcodeWrapper.toEntity(yxfpQrcodeDTO));
        }
        return ResponseEntity.ok("小程序码生成成功");
    }
}
